package com.bml.architect.framework;

import com.bml.architect.framework.protocol.Protocol;
import com.bml.architect.framework.protocol.http.HttpClient;
import com.bml.architect.framework.register.AddressRegister;
import com.bml.architect.framework.register.ZookeeperRegister;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;
import java.util.Random;

public class ProxyFactory {


    @SuppressWarnings(value = "unchecked")
    public static <T> T getProxy(Class<?> interfaces) {

        return (T) Proxy.newProxyInstance(interfaces.getClassLoader(), new Class<?>[]{interfaces}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                Invocation invocation = new Invocation(interfaces.getName(), method.getName(), method.getParameterTypes()
                        , args);
                Protocol protocol = ProtocolFactory.getProtocol();
               // List<Address> list = AddressRegister.getAddress(interfaces.getName());
                List<Address> list = ZookeeperRegister.get(interfaces.getName());
                Address address = getLoadBalance(list);
                String result = protocol.send(address, invocation);
                return result;
            }
        });
    }

    private static Address getLoadBalance(List<Address> list) {
        Random dom = new Random();
        return list.get(dom.nextInt(list.size()));
    }
}
